<template>
    <div class="form-container">
        <header>
            <span>
                <el-page-header content="发票申请" @back="onClose" />
            </span>
            <span>
                <el-button v-if="showSaveBtn" type="primary" @click="onSubmit">保存</el-button>
                <el-button v-if="showReviewBtn" type="primary" @click="onReview">审核</el-button>
                <el-button type="default" @click="onPrint">打印</el-button>
            </span>
        </header>
        <div class="form-content">
            <el-form :model="ruleForm" class="form-info" :rules="rules" ref="ruleFormRef">
                <span class="form-title">收款信息</span>
                <el-form-item label="开票日期" prop="invoiceDate">
                    <el-date-picker
                        v-model="ruleForm.invoiceDate"
                        placeholder="请选择开票日期"
                        type="date"
                        value-format="YYYY-MM-DD"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="项目编号" prop="projectCode">
                    <el-input
                        v-model="ruleForm.projectCode"
                        placeholder="请选择项目"
                        readonly
                        @click.native="projectChoose"
                    ></el-input>
                </el-form-item>
                <el-form-item label="项目名称" prop="projectName">
                    <el-input
                        v-model="ruleForm.projectName"
                        placeholder="请选择项目"
                        readonly
                        @click.native="projectChoose"
                    ></el-input>
                </el-form-item>
                <el-form-item label="业主单位" prop="clientCompanyName">
                    <el-input
                        v-model="ruleForm.clientCompanyName"
                        placeholder="请选择业主单位"
                        readonly
                        @click.native="companyChoose('clientCompanyName')"
                    ></el-input>
                </el-form-item>
                <el-form-item label="预计到账时间" prop="expectedArrivalTime">
                    <el-date-picker
                        v-model="ruleForm.expectedArrivalTime"
                        placeholder="请选择预计到账时间"
                        type="date"
                        value-format="YYYY-MM-DD"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="发票金额(元)" prop="fapiaoAmount">
                    <el-input v-model="ruleForm.fapiaoAmount" placeholder="请输入发票金额，单位：元"></el-input>
                </el-form-item>
                <el-form-item label="发票摘要" prop="fapiaoAbsrtact" class="risk-textarea">
                    <el-input
                        type="textarea"
                        placeholder="请输入发票摘要"
                        v-model="ruleForm.fapiaoAbsrtact"
                        maxlength="100"
                        show-word-limit
                        :rows="4"
                    ></el-input>
                </el-form-item>
                <el-form-item label="发票备注" prop="fapiaoRemark" class="risk-textarea">
                    <el-input
                        type="textarea"
                        placeholder="请输入发票备注"
                        v-model="ruleForm.fapiaoRemark"
                        maxlength="200"
                        show-word-limit
                        :rows="4"
                    ></el-input>
                </el-form-item>
                <el-form-item label="是否开具收据" prop="needReceipt">
                    <el-radio-group v-model="ruleForm.needReceipt">
                        <el-radio :label="0">否</el-radio>
                        <el-radio :label="1">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="付款单位名称" prop="payer">
                    <el-input
                        v-model="ruleForm.payer"
                        placeholder="请选择付款单位名称"
                        readonly
                        @click.native="companyChoose('payer')"
                    ></el-input>
                </el-form-item>
                <el-form-item label="纳税人识别号" prop="payerTaxIdNo">
                    <el-input v-model="ruleForm.payerTaxIdNo" readonly></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="payerAddress">
                    <el-input v-model="ruleForm.payerAddress" readonly></el-input>
                </el-form-item>
                <el-form-item label="开户行" prop="payerBankName">
                    <el-input v-model="ruleForm.payerBankName" readonly></el-input>
                </el-form-item>
                <el-form-item label="账号" prop="payerBankNo">
                    <el-input v-model="ruleForm.payerBankNo" readonly></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="payerTelphone">
                    <el-input v-model="ruleForm.payerTelphone" readonly></el-input>
                </el-form-item>
                <!-- <el-form-item label="状态" prop="state" v-if="formTitle === '查看'?true:false">
                    <el-input v-model="ruleForm.stateCn"  readonly></el-input>
                </el-form-item>
                <el-form-item label="当前处理人" prop="currentHandler" v-if="formTitle === '查看'?true:false">
                    <el-input v-model="ruleForm.currentHandler" ></el-input>
                </el-form-item> -->
                <!-- <el-form-item label=" " v-if="formTitle === '查看'?false:true"></el-form-item>
                <el-form-item label=" " v-if="formTitle === '查看'?false:true"></el-form-item>
                <el-form-item label=" " v-if="formTitle === '查看'?false:true"></el-form-item> -->
                <span class="form-title">附件信息</span>
                <div style="width: 100%">
                    <div v-show="showSaveBtn" style="padding: 10px">
                        <el-upload
                            :action="uploadUrl"
                            :headers="uploadHeaders"
                            :on-success="onFileUploadSuccess"
                            :show-file-list="false"
                        >
                            <el-button type="primary">点击上传</el-button>
                        </el-upload>
                    </div>
                    <el-table :data="ruleForm.attachments" border>
                        <el-table-column type="index" width="80" label="序号" />
                        <el-table-column prop="fileName" label="文件名" />
                        <el-table-column prop="createTime" label="上传时间" width="200" />
                        <el-table-column fixed="right" label="操作" width="200">
                            <template #default="scope">
                                <el-button type="primary" @click="handlePreview(scope.row)" size="small">
                                    预览
                                </el-button>
                                <el-button
                                    type="danger"
                                    @click.prevent="handleRemove(scope.$index, ruleForm.attachments)"
                                    size="small"
                                >
                                    移除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <span class="form-title">审批流程</span>
                <FlowCpt
                    ref="processRef"
                    :flowType="flowTypeCode"
                    :disabled="!showSaveBtn"
                    :taskId="props.taskId"
                ></FlowCpt>
                <FlowOperationCpt
                    v-if="showReviewDialog"
                    :data="ruleForm"
                    @close="closeReviewDialog"
                ></FlowOperationCpt>
                <span class="form-title" v-if="showFlowHis">审批记录</span>
                <FlowHistoryCpt v-if="showFlowHis" :taskId="props.taskId" />
            </el-form>
        </div>
        <!-- 项目弹框 -->
        <el-dialog
            title="选择人员"
            v-model="showProjectGridCpt"
            width="80%"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <ProjectGridCpt v-if="showProjectGridCpt" @select="projectRow"></ProjectGridCpt>
        </el-dialog>
        <!-- 单位弹框 -->
        <el-dialog
            title="选择单位"
            v-model="showCompanyGridCpt"
            width="80%"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <CompanyGridCpt v-if="showCompanyGridCpt" @select="companyRow"></CompanyGridCpt>
        </el-dialog>
        <el-dialog
            width="840px"
            top="10vh"
            title="打印预览"
            v-model="showPrint"
            :lock-scroll="true"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <PrintTemplate :id="props.taskId"></PrintTemplate>
        </el-dialog>
    </div>
</template>
<script setup>
import { reactive, ref, unref, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import http from '@/http.js'
import ProjectGridCpt from '@/components/pub/ProjectGridCpt.vue'
import CompanyGridCpt from '@/components/pub/CompanyGridCpt.vue'
import PrintTemplate from '@/print/yunying/FapiaoPrint.vue'
import FlowCpt from '@/components/process/FlowCpt.vue'
import FlowOperationCpt from '@/components/process/FlowOperationCpt.vue'
import FlowHistoryCpt from '@/components/process/FlowHistoryCpt.vue'

const props = defineProps({
    taskId: {
        type: String,
        default: ''
    }
})

// 返回主页面,子组件向父组件传值
const emit = defineEmits(['close'])
const onClose = () => {
    emit('close')
}

onMounted(() => {
    if (props.taskId !== '') {
        loadDetail()
    } else {
        showSaveBtn.value = true
    }
})

const flowTypeCode = 'FAPIAO'

const rules = {
    invoiceDate: [{ required: true, message: '', trigger: 'change' }],
    projectCode: [{ required: true, message: '', trigger: 'change' }],
    projectName: [{ required: true, message: '', trigger: 'change' }],
    clientCompanyName: [{ required: true, message: '', trigger: 'change' }],
    fapiaoAmount: [{ required: true, message: '', trigger: 'blur' }],
    expectedArrivalTime: [{ required: true, message: '', trigger: 'change' }],
    needReceipt: [{ required: true, message: '', trigger: 'change' }],
    payer: [{ required: true, message: '', trigger: 'change' }]
    // payerTaxIdNo: [{ required: true, message: '', trigger: 'change' }],
    // payerBankName: [{ required: true, message: '', trigger: 'change' }],
    // payerBankNo: [{ required: true, message: '', trigger: 'change' }]
}
// 表单初始化
let ruleForm = reactive({
    invoiceDate: '',
    projectCode: '',
    projectName: '',
    currentHandler: '',
    clientCompanyName: '',
    fapiaoAmount: '',
    expectedArrivalTime: '',
    fapiaoAbsrtact: '',
    fapiaoRemark: '',
    needReceipt: '',
    payer: '',
    payerTaxIdNo: '',
    payerAddress: '',
    payerBankName: '',
    payerBankNo: '',
    payerTelphone: '',
    attachments: [],
    flowTypeCode: flowTypeCode,
    state: '',
    stateName: '',
    handler: '',
    handlerName: ''
})

const processRef = ref(null)
const showSaveBtn = ref(false)
const showReviewBtn = ref(false)
const showReviewDialog = ref(false)
const showFlowHis = ref(false)

const loadDetail = (taskId, taskType) => {
    http.fetchForm({
        url: '/yunying/fapiao/findById',
        data: {
            id: props.taskId
        }
    }).then((res) => {
        // 基本信息
        Object.assign(ruleForm, res.data)

        // 显示保存按钮条件
        let currentUser = localStorage.getItem('username')
        if (ruleForm.state == 0 && ruleForm.createBy === currentUser) {
            showSaveBtn.value = true
        } else {
            showSaveBtn.value = false
        }
        // 显示审批按钮条件
        if (ruleForm.state != 0 && ruleForm.handler === currentUser) {
            showReviewBtn.value = true
        } else {
            showReviewBtn.value = false
        }
        // 显示流程历史
        showFlowHis.value = true

        if (ruleForm.fapiaoAmount !== '') {
            ruleForm.fapiaoAmount = (parseFloat(ruleForm.fapiaoAmount) / 100).toFixed(2)
        }
    })
}

// 表单提交
const ruleFormRef = ref(null)
const onSubmit = async () => {
    if (validate(ruleForm)) {
        let params = JSON.parse(JSON.stringify(ruleForm))
        params.fapiaoAmount = parseFloat(params.fapiaoAmount) * 100
        let processData = processRef.value.processList
        params['flowList'] = processData
        http.fetchJson({
            url: 'yunying/fapiao/save',
            data: params
        }).then((res) => {
            ElNotification({
                title: '提示',
                message: '操作成功',
                type: 'success'
            })
            onClose()
        })
    } else {
        ElNotification({
            title: '提示',
            message: '打*项必填',
            type: 'warning'
        })
    }
}

// 判断必填字段
const validate = (ruleForm) => {
    if (ruleForm.projectCode === null || ruleForm.projectCode === '') return false
    if (ruleForm.projectName === null || ruleForm.projectName === '') return false
    if (ruleForm.invoiceDate === null || ruleForm.invoiceDate === '') return false
    if (ruleForm.clientCompanyName === null || ruleForm.clientCompanyName === '') return false
    if (ruleForm.fapiaoAmount === null || ruleForm.fapiaoAmount === '') return false
    if (ruleForm.expectedArrivalTime === null || ruleForm.expectedArrivalTime === '') return false
    if (ruleForm.needReceipt === null || ruleForm.needReceipt === '') return false
    if (ruleForm.payer === null || ruleForm.payer === '') return false
    // if (ruleForm.payerTaxIdNo === null || ruleForm.payerTaxIdNo === '') return false
    // if (ruleForm.payerBankName === null || ruleForm.payerBankName === '') return false
    // if (ruleForm.payerBankNo === null || ruleForm.payerBankNo === '') return false
    return true
}

// 重置
const reset = () => {
    const form = unref(ruleFormRef)
    form.resetField()
}

// 审核
const onReview = (refresh) => {
    showReviewDialog.value = true
}

const closeReviewDialog = (refresh) => {
    showReviewDialog.value = false
    if (refresh) {
        loadDetail()
    }
}

// 项目选择
const showProjectGridCpt = ref(false)
const projectChoose = () => {
    showProjectGridCpt.value = true
}

const projectRow = (params) => {
    ruleForm.projectName = params[0].name
    ruleForm.projectCode = params[0].code
    showProjectGridCpt.value = false
}

// 单位选择
const showCompanyGridCpt = ref(false)
let flag = ''
const companyChoose = (params) => {
    flag = params
    showCompanyGridCpt.value = true
}

const companyRow = (params) => {
    if (flag === 'clientCompanyName') {
        ruleForm.clientCompanyName = params[0].name
    } else {
        ruleForm.payer = params[0].name
        ruleForm.payerTaxIdNo = params[0].taxIdNo
        ruleForm.payerAddress = params[0].address
        ruleForm.payerBankName = params[0].bankName
        ruleForm.payerBankNo = params[0].bankNo
        ruleForm.payerTelphone = params[0].telphone
    }
    showCompanyGridCpt.value = false
}

// 打印
const showPrint = ref(false)
const onPrint = () => {
    showPrint.value = true
}

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/sys/file/upload')
const uploadHeaders = reactive({
    Authorization: localStorage.getItem('token')
})

const onFileUploadSuccess = (response) => {
    let json = {
        category: 0,
        fileName: response.data.fileName,
        storageName: response.data.storageName,
        storagePath: response.data.storagePath
    }
    ruleForm.attachments.push(json)
}

const handlePreview = (row) => {
    let url = import.meta.env.VITE_API_URL + '/attachment/' + row.storageName
    window.open(url)
}

const handleRemove = (index, rows) => {
    rows.splice(index, 1)
}
</script>
<style scoped>
@import '@/assets/css/form.css';
</style>
